﻿using BCCommon.Enums;
using BCData.WeChatComponent.WeChatKeyword;
using BCData.WeChatComponent.WeChatMediaRecord;
using BCData.WeChatComponent.WeChatMessageRecord;
using BCData.WeChatComponent.WeChatNewsMaterialArticleRecord;
using BCEntity.WeChatComponent.WeChatKeyword;
using BCEntity.WeChatComponent.WeChatMediaRecord;
using BCEntity.WeChatComponent.WeChatMessageRecord;
using BCEntity.WeChatComponent.WeChatNewsMaterialArticleRecord;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WeChatSDK.Common;
using WeChatSDK.WeChatDto.Conversation.ReceivingMessage;
using WeChatSDK.WeChatDto.Conversation.ReplyMessage;

namespace BCService.WeChatComponent.WeChatHandleService
{
    /// <summary>
    /// 微信文本消息处理
    /// </summary>
    public class TextMessageService : IWeChatMessageHandle
    {
        private readonly IWeChatKeywordData weChatKeywordData;
        private readonly IWeChatMessageRecordData weChatMessageRecordData;
        private readonly IWeChatMediaRecordData weChatMediaRecordData;
        private readonly IWeChatNewsMaterialArticleRecordData weChatNewsMaterialArticleRecordData;

        ///*宝徕红包使用业务*/
        //private readonly IBrokerService brokerService;
        //private readonly IRedEnvelopeService redEnvelopeService;
        public TextMessageService(IWeChatKeywordData weChatKeywordData,
            IWeChatMessageRecordData weChatMessageRecordData,
            IWeChatMediaRecordData weChatMediaRecordData,
            IWeChatNewsMaterialArticleRecordData weChatNewsMaterialArticleRecordData)
            //,
            //IBrokerService brokerService,
            //IRedEnvelopeService redEnvelopeService)
        {
            this.weChatKeywordData = weChatKeywordData;
            this.weChatMessageRecordData = weChatMessageRecordData;
            this.weChatMediaRecordData = weChatMediaRecordData;
            this.weChatNewsMaterialArticleRecordData = weChatNewsMaterialArticleRecordData;
            //this.brokerService = brokerService;
            //this.redEnvelopeService = redEnvelopeService;
        }

        public string HandleMessage(ReceivingMessageDto message)
        {
            TextMessageDto textMessageDto = (TextMessageDto)message;
            WeChatKeywordEntity entity = weChatKeywordData.GetWeChatKeyword(textMessageDto.Content);
            WeChatMessageRecordEntity weChatMessageRecordEntity = this.RecordReceivingMessage(textMessageDto);
            string response = "success";
            ReplyMessageDto replyMessageDto = new ReplyMessageDto();
            if (entity == null)
            {
                if (textMessageDto.Content.Contains("红包"))
                {
                    string[] messageKey = textMessageDto.Content.Split(",");
                    try
                    {

                        string uniqueCode = messageKey[0].Split(":")[1];
                        string emoloyeeId = messageKey[1].Split(":")[1];
                        string contractNo = messageKey[2].Split(":")[1];
                        if (!messageKey[0].Split(":")[0].Contains("红包")|| uniqueCode.Length!=8)
                        {
                            throw new ArgumentException("红包编号不正确！");
                        }
                        if (!messageKey[1].Split(":")[0].Contains("经纪人"))
                        {
                            throw new ArgumentException("经纪人账号不正确！");
                        }
                        if (!messageKey[2].Split(":")[0].Contains("合同"))
                        {
                            throw new ArgumentException("合同编号不正确！");
                        }
                        //this.redEnvelopeService.UsedRedEnvelope(uniqueCode, emoloyeeId, contractNo);
                        replyMessageDto = new TextReplyMessageDto()
                        {
                            CreateTime = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", "")),
                            Content = "已成功使用此红包",
                            FromUserName = message.ToUserName,
                            ToUserName = message.FromUserName,
                            MsgType = WeChatReplyType.Text.ToString().ToLower()
                        };
                        this.weChatMessageRecordData.UpdateRepliedStatus(weChatMessageRecordEntity.WeChatMessageRecordId);
                        return WeChatXmlUtils.SerializeToXml(replyMessageDto);
                    }
                    catch (ArgumentException ex)
                    {
                        replyMessageDto = new TextReplyMessageDto()
                        {
                            CreateTime = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", "")),
                            Content = ex.Message,
                            FromUserName = message.ToUserName,
                            ToUserName = message.FromUserName,
                            MsgType = WeChatReplyType.Text.ToString().ToLower()
                        };
                        this.weChatMessageRecordData.UpdateRepliedStatus(weChatMessageRecordEntity.WeChatMessageRecordId);
                        return WeChatXmlUtils.SerializeToXml(replyMessageDto);
                    }
                }
                else
                {
                    return response;
                }
            }
            
            switch (entity.ReplyType)
            {
                case WeChatReplyType.Text:
                    TextReplyMessageDto textReplyMessageDto = new TextReplyMessageDto()
                    {
                        CreateTime = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", "")),
                        Content = entity.Content,
                        FromUserName = message.ToUserName,
                        ToUserName = message.FromUserName,
                        MsgType = WeChatReplyType.Text.ToString().ToLower()
                    };
                    this.RecordReplyMessage(textReplyMessageDto, weChatMessageRecordEntity.WeChatMessageRecordId);
                    replyMessageDto = textReplyMessageDto;
                    break;
                case WeChatReplyType.Image:
                    replyMessageDto = this.GetImageReplyMessage(entity, message.FromUserName, message.ToUserName, weChatMessageRecordEntity.WeChatMessageRecordId);
                    break;
                case WeChatReplyType.Music:
                    replyMessageDto = this.GetMusicReplyMessage(entity, message.FromUserName, message.ToUserName, weChatMessageRecordEntity.WeChatMessageRecordId);
                    break;
                case WeChatReplyType.News:
                    replyMessageDto = this.GetNewsReplyMessage(entity, message.FromUserName, message.ToUserName, weChatMessageRecordEntity.WeChatMessageRecordId);
                    break;
                case WeChatReplyType.Video:
                    replyMessageDto = this.GetVideoReplyMessage(entity, message.FromUserName, message.ToUserName, weChatMessageRecordEntity.WeChatMessageRecordId);
                    break;
                case WeChatReplyType.Voice:
                    replyMessageDto = this.GetVoiceReplyMessage(entity, message.FromUserName, message.ToUserName, weChatMessageRecordEntity.WeChatMessageRecordId);
                    break;
            }
            this.weChatMessageRecordData.UpdateRepliedStatus(weChatMessageRecordEntity.WeChatMessageRecordId);
            return WeChatXmlUtils.SerializeToXml(replyMessageDto);
        }
        private WeChatMessageRecordEntity RecordReceivingMessage(TextMessageDto textMessageDto)
        {
            WeChatMessageRecordEntity entity = new WeChatMessageRecordEntity()
            {
                ToUserName = textMessageDto.ToUserName,
                FromUserName = textMessageDto.FromUserName,
                Content = textMessageDto.Content,
                MessageType = WeChatMessageType.Text,
                MessageId = textMessageDto.MsgId,
                IsReply = false
            };
            return this.weChatMessageRecordData.Add(entity);
        }
        private void RecordReplyMessage(TextReplyMessageDto textReplyMessageDto, long msgId)
        {
            WeChatMessageRecordEntity entity = new WeChatMessageRecordEntity()
            {
                ToUserName = textReplyMessageDto.ToUserName,
                FromUserName = textReplyMessageDto.FromUserName,
                Content = textReplyMessageDto.Content,
                MessageType = WeChatMessageType.Text,
                MessageId = msgId,
                IsReply = true
            };
            this.weChatMessageRecordData.Add(entity);
        }
        private ImageReplyMessageDto GetImageReplyMessage(WeChatKeywordEntity entity, string toUserFrom, string fromUserName, long msgId)
        {
            ImageReplyMessageDto imageReplyMessageDto = new ImageReplyMessageDto();
            imageReplyMessageDto.CreateTime = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", ""));
            imageReplyMessageDto.FromUserName = fromUserName;
            imageReplyMessageDto.ToUserName = toUserFrom;
            imageReplyMessageDto.MsgType = entity.ReplyType.ToString().ToLower();
            imageReplyMessageDto.MediaId = entity.MediaId;

            WeChatMessageRecordEntity messageRecordEntity = new WeChatMessageRecordEntity()
            {
                ToUserName = toUserFrom,
                FromUserName = fromUserName,
                MessageType = WeChatMessageType.Image,
                MessageId = msgId,
                MediaId = entity.MediaId,
                IsReply = true
            };
            this.weChatMessageRecordData.Add(messageRecordEntity);
            return imageReplyMessageDto;
        }
        private MusicReplyMessageDto GetMusicReplyMessage(WeChatKeywordEntity entity, string toUserFrom, string fromUserName, long msgId)
        {
            WeChatMediaRecordEntity mediaRecordEntity = this.weChatMediaRecordData.GetEntity(entity.MediaId);
            MusicReplyMessageDto musicReplyMessageDto = new MusicReplyMessageDto();
            musicReplyMessageDto.CreateTime = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", ""));
            musicReplyMessageDto.Description = mediaRecordEntity.Description;
            musicReplyMessageDto.FromUserName = fromUserName;
            musicReplyMessageDto.ToUserName = toUserFrom;
            musicReplyMessageDto.HQMusicUrl = mediaRecordEntity.LocalUrl;
            musicReplyMessageDto.MsgType = entity.ReplyType.ToString().ToLower();
            musicReplyMessageDto.MusicURL = mediaRecordEntity.LocalUrl;
            musicReplyMessageDto.ThumbMediaId = entity.ThumbMediaId;
            musicReplyMessageDto.Title = mediaRecordEntity.Title;

            WeChatMessageRecordEntity messageRecordEntity = new WeChatMessageRecordEntity()
            {
                ToUserName = toUserFrom,
                FromUserName = fromUserName,
                MessageType = WeChatMessageType.Music,
                MessageId = msgId,
                MediaId = entity.MediaId,
                Title = mediaRecordEntity.Title,
                Description = mediaRecordEntity.Description,
                ThumbMediaId = entity.ThumbMediaId,
                IsReply = true
            };
            this.weChatMessageRecordData.Add(messageRecordEntity);
            return musicReplyMessageDto;
        }
        private NewsReplyMessageDto GetNewsReplyMessage(WeChatKeywordEntity entity, string toUserFrom, string fromUserName, long msgId)
        {
            IEnumerable<WeChatNewsMaterialArticleRecordEntity> weChatNewsMaterialArticleRecordEntities = this.weChatNewsMaterialArticleRecordData.Get(entity.MediaId);
            NewsReplyMessageDto newsReplyMessageDto = new NewsReplyMessageDto();
            newsReplyMessageDto.CreateTime = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", ""));
            newsReplyMessageDto.FromUserName = fromUserName;
            newsReplyMessageDto.ToUserName = toUserFrom;
            newsReplyMessageDto.MsgType = entity.ReplyType.ToString().ToLower();
            newsReplyMessageDto.ArticleCount = weChatNewsMaterialArticleRecordEntities.Count();
            List<NewsItemArticlesDto> newsItemArticlesDtos = new List<NewsItemArticlesDto>();

            foreach (WeChatNewsMaterialArticleRecordEntity article in weChatNewsMaterialArticleRecordEntities.OrderBy(p => p.Index))
            {
                NewsItemArticlesDto newsItemArticlesDto = new NewsItemArticlesDto();
                newsItemArticlesDto.PicUrl = article.ThumbUrl;
                newsItemArticlesDto.Title = article.Title;
                newsItemArticlesDto.Description = article.Digest;
                newsItemArticlesDto.Url = article.ContentSourceUrl;
                newsItemArticlesDtos.Add(newsItemArticlesDto);
            }
            newsReplyMessageDto.Articles = newsItemArticlesDtos;

            WeChatNewsMaterialArticleRecordEntity weChatNewsMaterialArticleRecordEntity = weChatNewsMaterialArticleRecordEntities.First(p => p.Index == 0);
            WeChatMessageRecordEntity messageRecordEntity = new WeChatMessageRecordEntity()
            {
                ToUserName = toUserFrom,
                FromUserName = fromUserName,
                MessageType = WeChatMessageType.News,
                MessageId = msgId,
                MediaId = entity.MediaId,
                Title = weChatNewsMaterialArticleRecordEntity.Title,
                Description = weChatNewsMaterialArticleRecordEntity.Digest,
                IsReply = true
            };
            this.weChatMessageRecordData.Add(messageRecordEntity);
            return newsReplyMessageDto;
        }
        private VideoReplyMessageDto GetVideoReplyMessage(WeChatKeywordEntity entity, string toUserFrom, string fromUserName, long msgId)
        {
            WeChatMediaRecordEntity mediaRecordEntity = this.weChatMediaRecordData.GetEntity(entity.MediaId);
            VideoReplyMessageDto videoReplyMessageDto = new VideoReplyMessageDto();
            videoReplyMessageDto.CreateTime = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", ""));
            videoReplyMessageDto.Description = mediaRecordEntity.Description;
            videoReplyMessageDto.FromUserName = fromUserName;
            videoReplyMessageDto.ToUserName = toUserFrom;
            videoReplyMessageDto.MsgType = entity.ReplyType.ToString().ToLower();
            videoReplyMessageDto.Title = mediaRecordEntity.Title;
            videoReplyMessageDto.MediaId = entity.MediaId;
            WeChatMessageRecordEntity messageRecordEntity = new WeChatMessageRecordEntity()
            {
                ToUserName = toUserFrom,
                FromUserName = fromUserName,
                MessageType = WeChatMessageType.Video,
                MessageId = msgId,
                MediaId = entity.MediaId,
                IsReply = true
            };
            this.weChatMessageRecordData.Add(messageRecordEntity);
            return videoReplyMessageDto;
        }
        private VoiceReplyMessageDto GetVoiceReplyMessage(WeChatKeywordEntity entity, string toUserFrom, string fromUserName, long msgId)
        {
            WeChatMediaRecordEntity mediaRecordEntity = this.weChatMediaRecordData.GetEntity(entity.MediaId);
            VoiceReplyMessageDto voiceReplyMessageDto = new VoiceReplyMessageDto();
            voiceReplyMessageDto.CreateTime = int.Parse(Regex.Replace(DateTime.Now.ToShortDateString(), "[^\\d]", ""));
            voiceReplyMessageDto.FromUserName = fromUserName;
            voiceReplyMessageDto.ToUserName = toUserFrom;
            voiceReplyMessageDto.MsgType = entity.ReplyType.ToString().ToLower();
            voiceReplyMessageDto.MediaId = entity.MediaId;
            WeChatMessageRecordEntity messageRecordEntity = new WeChatMessageRecordEntity()
            {
                ToUserName = toUserFrom,
                FromUserName = fromUserName,
                MessageType = WeChatMessageType.Voice,
                MessageId = msgId,
                MediaId = entity.MediaId,
                IsReply = true
            };
            this.weChatMessageRecordData.Add(messageRecordEntity);
            return voiceReplyMessageDto;
        }
    }
}
